<?php

namespace app\index\controller;

use app\index\controller\Base;
use http\Params;
use think\Config;
use think\Db;
use think\Session;

class User extends Base
{
    /**
     * 个人信息首页
     * @return mixed
     */
    public function Index()
    {
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);

        $Str = "&nbsp;&nbsp;&nbsp;";
        $Str1 = substr($UserInfo['username'],0,4);
        $Str2 = substr($UserInfo['username'],4,4);
        $Str3 = substr($UserInfo['username'],8,4);

        $UserInfo['new_username'] = $Str1.$Str.$Str2.$Str.$Str3;

        //等级信息
        $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
        $UserInfo['level_name'] = $LevelInfo['name'];
//        var_dump($UserInfo);die;
        $this->assign('UserInfo',$UserInfo);

        //推荐的产品
        $GoodsList = Db::name('goods')->where(['is_recommend'=>2,'is_shelf'=>2])->select();
        $this->assign('GoodsList',$GoodsList);

        //订单数量
        //全部订单
        $Where['user_id'] = Session::get('user_id');
        $OrderListAll = Db::name('user_order')->where($Where)->count();
        $this->assign('OrderListAll',$OrderListAll);

        //待付款订单
        $Where['status'] = 0;
        $OrderList_0 = Db::name('user_order')->where($Where)->count();
        $this->assign('OrderList_0',$OrderList_0);

        //待发货订单
        $Where['status'] = 1;
        $OrderList_1 = Db::name('user_order')->where($Where)->count();
        $this->assign('OrderList_1',$OrderList_1);

        //待收货订单
        $Where['status'] = 2;
        $OrderList_2 = Db::name('user_order')->where($Where)->count();
        $this->assign('OrderList_2',$OrderList_2);

        //已完成订单
        $Where['status'] = 3;
        $OrderList_3 = Db::name('user_order')->where($Where)->count();
        $this->assign('OrderList_3',$OrderList_3);

        return $this->fetch('Index');
    }

    /**
     * 用户设置
     * @return mixed
     */
    public function UserSetup(){
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);
        
        //查看当前用户有没有下级   有下级不能改推荐人
        // $downinfo = UserInfo(['recommend'=>$UserInfo['id']]);
        // $this->assign('downinfo',$downinfo);
        return $this->fetch("UserSetup");
    }
    
    //修改直推人
    public function Usertui(){
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);
        //原上级
        $recommendinfo = UserInfo(['id'=>$UserInfo['recommend']]);
        $this->assign('recommendinfo',$recommendinfo);
        if(IsPost()){
            $Data = Param();
            //新推荐人信息
            $Recommend = UserInfo(['username'=>$Data['newtui']]);
            if (!$Recommend){
                return ['status'=>0,'message'=>'推荐人不存在'];
            }
            //删除之前的推荐关系  user_id 就行
            if(Db::name('user_recommend')->where(['user_id'=>$UserInfo['id']])->delete()){
                
                //recommend_count - 1
                $oldup['recommend_count'] = $recommendinfo['recommend_count'] - 1;
                Db::name('user')->where(['id'=>$recommendinfo['id']])->update($oldup);
                
                //修改自己的新上级
                $newrecommend['recommend'] = $Recommend['id'];
                Db::name('user')->where(['id'=>$UserInfo['id']])->update($newrecommend);
                
                //创建推荐关系
                $user_id = $UserInfo['id'];
                $recommend_id = $Recommend['id'];
                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend_id]);
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>2,'message'=>'修改失败'];
            }
        }
        return $this->fetch("Usertui");
    }

    /**
     * 个人资料
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserInfo(){
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);
        if(IsPost()){
            $Data = Param();
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($Data) !== false){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'系统问题,请稍候再试'];
            }
        }
        return $this->fetch('UserInfo');
    }

    /**
     * 地址列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function AddressList(){
        //地址列表
        $AddressList = Db::name('user_address')->where(['user_id'=>Session::get('user_id')])->order('is_default desc')->select();
        $this->assign('AddressList',$AddressList);
        
        $goods_id = param('goods_id');
        $this->assign('goods_id',$goods_id);
        return $this->fetch('AddressList');
    }

    public function AddressList_1(){
        //地址列表
        $AddressList = Db::name('user_address')->where(['user_id'=>Session::get('user_id')])->order('is_default desc')->select();
        $this->assign('AddressList',$AddressList);
        
        $goods_id = param('goods_id');
        $this->assign('goods_id',$goods_id);
        return $this->fetch('AddressList_1');
    }

    /**
     *  添加地址
     * @return mixed
     */
    public function AddressAdd(){
        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();
            $Data['user_id'] = Session::get('user_id');

            //第一条地址设为默认
            $AddressCount = Db::name('user_address')->where(['user_id'=>$Data['user_id']])->count();
            if($AddressCount == 0){
                $Data['is_default'] = 1;
            }

            //向表中添加数据
            if(Db::name('user_address')->insert($Data)){
                return ['status'=>1,'message'=>'添加成功！'];
            }else{
                return ['status'=>0,'message'=>'添加失败，请重试！'];
            }

        }
        $goods_id = param('goods_id');
        // var_dump($goods_id);die;
        $this->assign('goods_id',$goods_id);
        return $this->fetch('AddressAdd');
    }

    /**
     * 设置默认地址
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function AddressDefault(){
        //Post请求
        if(IsPost()){
            //先取消全部默认
            Db::name('user_address')->where(['user_id'=>Session::get('user_id')])->update(['is_default'=>0]);
            //对指定的地址添加默认
            $AddressID = Param('address_id');
            if(Db::name('user_address')->where(['id'=>$AddressID])->update(['is_default'=>1])){
                return ['status'=>1,'message'=>'设置成功！'];
            }else{
                return ['status'=>1,'message'=>'系统错误，请重试！'];
            }
        }
    }

    /**
     * 删除地址
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function AddressDelete(){
        //Post请求
        if(IsPost()){
            //对指定的地址进行删除
            $AddressID = Param('address_id');
            if(Db::name('user_address')->where(['id'=>$AddressID])->delete()){
                return ['status'=>1,'message'=>'删除成功！'];
            }else{
                return ['status'=>1,'message'=>'系统错误，请重试！'];
            }
        }
    }

    /**
     * 申请等级
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserLevel(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);

        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();

            //判断申请等级是否相同
            if($Data['level_id'] == $UserInfo['level']){
                return ['status'=>0,'message'=>'申请类型和自身类型相同，不可申请'];
            }

            //判断当前是否有未处理的等级申请
            $Count = LevelApplyCount(['user_id'=>$UserInfo['id'],'status'=>0]);
            if($Count > 0){
                return ['status'=>0,'message'=>'存在未处理申请记录，请等待处理'];
            }

            //最近的一条申请记录
            $ApplyInfo = Db::name('user_level_apply')->where(['user_id'=>$UserInfo['id']])->order('add_time desc')->find();
            if(strtotime("+1months",$ApplyInfo['add_time']) > time()){
                return ['status'=>0,'message'=>'该申请每月只可提交一次'];
            }

            //添加申请记录
            $Data['user_id'] = $UserInfo['id'];
            $Data['add_time'] = time();
            $Data['save_level_id'] = $Data['level_id'];
          ;
            if(Db::name('user_level_apply')->insert($Data)){
                return ['status'=>1,'message'=>'已成功提交申请，待处理'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }

        }

        //定存金额
        $Deposit = Db::name('user_deposit')->where(['user_id'=>$UserInfo['id']])->sum('surplus_num');
        $this->assign('Deposit',$Deposit);

        //等级列表
        $LevelList = Db::name('user_level')->select();
        $this->assign('LevelList',$LevelList);

        //等级申请记录
        $LevelApply = Db::name('user_level_apply')->where(['user_id'=>$UserInfo['id']])->order('add_time desc')->select();
        foreach($LevelApply as $k=>$v){
            //等级信息
            $LevelInfo = LevelInfo(['id'=>$LevelApply[$k]['level_id']]);
            $LevelApply[$k]['level_name'] = $LevelInfo['name'];
        }
        $this->assign('LevelApply',$LevelApply);

        return $this->fetch('UserLevel');
    }

    /**
     * 银行信息
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function UserBank(){
        //银行信息
        $BankInfo = BankInfo(['user_id'=>Session::get('user_id')]);
        if(IsPost()){
            $Data = Param();
            $Data['user_id'] = Session::get('user_id');
            $Data['add_time'] = time();
            if (empty($BankInfo)){
                $Res = Db::name('user_bank')->insert($Data);
            }else{
                $Res = Db::name('user_bank')->where(['user_id'=>$Data['user_id']])->update($Data);
            }

            if($Res){
                return ['status'=>1,'message'=>'保存成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        $this->assign('BankInfo',$BankInfo);
        return $this->fetch('UserBank');
    }

    /**
     * 账户余额
     * @return User
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserBalance(){

        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        return $this->fetch('UserBalance');
    }

    /**
     * 会员充值
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserRecharge(){
        //系统参数
        $Config = Config();
        $this->assign('Config',$Config);

        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();
            //判断当前是否有未处理的充值记录
            $Count = Db::name('user_recharge')->where(['user_id'=>$UserInfo['id'],'status'=>0])->count();
            if($Count > 0){
                return ['status'=>0,'message'=>'当前拥有未处理的充值申请，请等待处理'];
            }

//            //判断验证码是否正确
//            $CodeRes = checkCode($UserInfo['phone'], $Data['code']);
//            if ($CodeRes['status'] != 1) {
//                return $CodeRes;
//            }

            //添加记录
            $AddData['user_id'] = $UserInfo['id'];
            $AddData['num'] = $Data['num'];
            $AddData['type'] = $Data['type'];
            $AddData['voucher_url'] = $Data['voucher_url'];
            $AddData['add_time'] = time();
            if(Db::name('user_recharge')->insert($AddData)){
                return ['status'=>1,"message"=>"充值记录已提交，请等待处理"];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }

        }

        //充值记录
        $RechargeList = Db::name('user_recharge')->where(['user_id'=>$UserInfo['id']])->order("add_time desc")->select();
        $this->assign("RechargeList",$RechargeList);

        return $this->fetch('UserRecharge');
    }
    
    //若用户无手机号  则填写
    public function addphone(){
        $phone = Param()['phone'];
        if(!preg_match("/^1[34578]\d{9}$/", $phone)){
            return ['status'=>0,'message'=>"请输入正确的手机号"];
        }
        
        $pd = Db::name('user')->where(['phone'=>$phone])->find();
        if($pd){
            return ['status'=>0,'message'=>"该手机号已存在"];
        }
        
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $data['phone'] = $phone;
        if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($data) !== false){
            return ['status'=>1,'message'=>"手机号填写成功"];
        }else{
            return ['status'=>0,'message'=>"系统错误,请稍候再试"];
        }
    }

    /**
     * 会员转账
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserTransfer(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        //系统参数
        $Config = Config();
        $this->assign('Config',$Config);

        //Post请求
        if (IsPost()) {
            //请求数据
            $Data = Param();
            //判断转入账号是否是自己
            if($Data['username'] == $UserInfo['phone']){
                return ['status'=>0,'message'=>"不可以给自己转账"];
            }
            
            //验证金额
            if($Data['num'] <= 0 || $Data['num'] == '' || !is_numeric($Data['num'])){
                return ['status'=>0,'message'=>"请输入正确的金额"];
            }
            
            //判断验证码是否正确
            $CodeRes = checkCode($Data['phone'],$Data['code']);
            // var_dump($CodeRes);die;
            if($CodeRes['status'] != 1){
                return $CodeRes;
            }
            
            //密码是否正确
            if(md5($Data['password']) != $UserInfo['password_pay']){
                return ['status'=>0,'message'=>"支付密码错误"];
            }

            //转入账号信息
            $ToUser = UserInfo(['phone'=> $Data['username']]);
            
            
            if(empty($ToUser)){
                return ['status'=>0,'message'=>"收款账号不存在"];
            }
            
            //转账手续费
            $Free = $Data['num'] * $Config['transfer_fees'];

            //总计金额 = 转账金额 + 手续费
            $TotalNum = $Data['num'] + $Free;

            //根据转账类型判断余额
            if($Data['type'] == 4){ //电子钱包余额
                if ($TotalNum > $UserInfo['balance_4']) {
                    return ['status' => 0, 'message' => "余额不足，当前余额" . $UserInfo['balance_4']];
                }else{
                    $UserSave['balance_4'] = $UserInfo['balance_4'] - $TotalNum;
                    $ToUserSave['balance_4'] = $ToUser['balance_4'] + $Data['num'];
                }
            }

            if($Data['type'] == 1){ //奖金
                if ($TotalNum > $UserInfo['balance_1']) {
                    return ['status' => 0, 'message' => "积分不足，当前积分" . $UserInfo['balance_1']];
                }else{
                    $UserSave['balance_1'] = $UserInfo['balance_1'] - $TotalNum;
                    $ToUserSave['balance_1'] = $ToUser['balance_1'] + $Data['num'];
                }
            }
            // if($Data['type'] == 2){ //炁点
            //     if ($TotalNum > $UserInfo['balance_2']) {
            //         return ['status' => 0, 'message' => "炁点余额不足，当前余额" . $UserInfo['balance_2']];
            //     }else{
            //         $UserSave['balance_2'] = $UserInfo['balance_2'] - $TotalNum;
            //         $ToUserSave['balance_2'] = $ToUser['balance_2'] + $Data['num'];
            //     }
            // }
            // if($Data['type'] == 3){ //股权
            //     if ($TotalNum > $UserInfo['balance_3']) {
            //         return ['status' => 0, 'message' => "股权余额不足，当前余额" . $UserInfo['balance_3']];
            //     }else{
            //         $UserSave['balance_3'] = $UserInfo['balance_3'] - $TotalNum;
            //         $ToUserSave['balance_3'] = $ToUser['balance_3'] + $Data['num'];
            //     }
            // }
//            //判断验证码是否正确
//            $CodeRes = checkCode($UserInfo['phone'], $Data['code']);
//            if ($CodeRes['status'] != 1) {
//                return $CodeRes;
//            }
            
            if($Data['type'] == 4){
                $chu = '余额转出';
                $ru = '余额转入';
            }elseif($Data['type'] == 1){
                $chu = '积分转出';
                $ru = '积分转入';
            }
            //扣除当前账户余额
            Db::name('user')->where(['id' => $UserInfo['id']])->update($UserSave);
            FinanceAdd($UserInfo['id'], $ToUser['id'], $Data['num'], $Data['type'], 7, $chu);
            //增加转入账户余额
            Db::name('user')->where(['id' => $ToUser['id']])->update($ToUserSave);
            FinanceAdd($ToUser['id'], $UserInfo['id'], $Data['num'], $Data['type'], 8, $ru);

            return ['status' => 1, 'message' => '转账成功'];
        }

        //转出/转进记录
        $Map['reward_type'] = array('in','7,8');
        $Map['user_id'] = $UserInfo['id'];
        $FinanceList = Db::name('finance')->where($Map)->order('add_time desc')->select();
        foreach($FinanceList as $k=>$v){
            $User = UserInfo(['id'=>$FinanceList[$k]['from_id']]);
            $FinanceList[$k]['username'] = $User['username'];
        }
        $this->assign('FinanceList',$FinanceList);

        return $this->fetch('UserTransfer');
    }

    /**
     * 会员提现
     * @return mixed
     */
    public function UserWithdraw(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign("UserInfo",$UserInfo);

        //银行信息
        $BankInfo = BankInfo(['user_id'=>Session::get('user_id')]);
        $this->assign('BankInfo',$BankInfo);

        //系统参数
        $Config = Config();
        $this->assign('Config',$Config);

        //Post请求
        if(IsPost()){
            //提现开关
            if($Config['withdraw_switch'] == 0){
                return ['status'=>0,'message'=>$Config['withdraw_prompt']];
            }

            //请求数据
            $Data = Param();

            $BeginTime = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $EndTime = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1);

            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
            $Where['user_id'] = $UserInfo['id'];
            $Count = Db::name('user_withdraw')->where($Where)->count();

            //判断当日提现次数
            if($Count > 0){
                return ['status'=>0,'message'=>'温馨提示：每天只能申请一次提现，提现到账时间为24-72小时。'];
            }
            
                        //验证金额
            if($Data['num'] <= 0 || $Data['num'] == '' || !is_numeric($Data['num'])){
                return ['status'=>0,'message'=>"请输入正确的金额"];
            }

            //最低提现
            if($Data['num'] < $Config['withdraw_down']){
                return ['status'=>0,'message'=>'提现金额不得少于'.$Config['withdraw_down']];
            }

            //提现整数倍
            if(($Data['num']%$Config['withdraw_multiple']) != 0){
                return ['status'=>0,'message'=>'提现金额须为'.$Config['withdraw_multiple'].'的整数倍'];
            }

            //判断是否保存银行信息
            if(empty($BankInfo)){
                return ['status'=>2,'message'=>'提现信息不完整，请完善提现信息'];
            }

            //提至
            if($Data['to_type'] == 1){  //银行卡
                if($BankInfo['bank_name'] =='' || $BankInfo['bank_open'] == '' || $BankInfo['bank_num'] == '' || $BankInfo['bank_user'] == ''){
                    return ['status'=>2,'message'=>'银行信息不完整，请完善银行信息'];
                }
            }

            if($Data['to_type'] == 2){  //支付宝
                if($BankInfo['ali_code'] ==''){
                    return ['status'=>2,'message'=>'未上传支付宝收款码'];
                }
            }

            if($Data['to_type'] == 3){  //微信
                if($BankInfo['ali_code'] ==''){
                    return ['status'=>2,'message'=>'未上传微信收款码'];
                }
            }


            //判断支付密码是否正确
            if(md5($Data['password']) != $UserInfo['password_pay']){
                return ['status'=>0,'message'=>'支付密码错误'];
            }
            //判断余额是否足够
            if($Data['num'] > $UserInfo['balance_4']){
                return ['status'=>0,'message'=>'余额不足'];
            }

//            //判断验证码是否正确
//            $CodeRes = checkCode($UserInfo['phone'], $Data['code']);
//            if ($CodeRes['status'] != 1) {
//                return $CodeRes;
//            }

            //更新余额
            $UserSave['balance_4'] = $UserInfo['balance_4'] - $Data['num'];
            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave)){
                $AddData = [
                    'user_id' => $UserInfo['id'],
                    'num' => $Data['num'],  //提现数量
                    'fees' => $Data['num'] * $Config['withdraw_fees'], //手续费
                    'real_num' => $Data['num'] - $Data['num'] * $Config['withdraw_fees'], //实际到账数量
                    'bank_name' => $BankInfo['bank_name'], //银行名称
                    'bank_open' => $BankInfo['bank_open'], //开户支行
                    'bank_num' => $BankInfo['bank_num'], //银行账号
                    'bank_user' => $BankInfo['bank_user'], //开户姓名
                    'ali_code' => $BankInfo['ali_code'], //支付宝收款码
                    'wechat_code' => $BankInfo['wechat_code'], //微信收款码
                    'to_type' => $Data['to_type'], //提现方式
                    'add_time' => time(),   //添加时间
                ];

                Db::name('user_withdraw')->insert($AddData);    //添加提现记录
                // FinanceAdd($UserInfo['id'],$UserInfo['id'],$Data['num'],1,9,'申请提现');
                FinanceAdd($UserInfo['id'],$UserInfo['id'],$Data['num'],4,9,'申请提现');

                return ['status'=>1,'message'=>'提交成功'];
            }else {
                return ['status' => 0, 'message' => '系统错误，请重试'];
            }
        }

        //提现记录
        $WithdrawList = Db::name('user_withdraw')->where(['user_id'=>$UserInfo['id']])->order('add_time desc')->select();
        $this->assign('WithdrawList',$WithdrawList);

        return $this->fetch('UserWithdraw');
    }

    /**
     * 余额转换
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserRechange(){
        //系统参数
        $Config = Config();
        $this->assign('Config',$Config);

        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        //POST请求
        if(IsPost()){
            $Data = Param();    //请求数据
            if(md5($Data['password']) !== $UserInfo['password_pay']){
                return ['status' => 0, 'message' => "支付密码错误"];
            }

            //根据转账类型判断余额
            if($Data['type'] == 2){ //炁点转换股权
                if ($Data['num'] > $UserInfo['balance_2']) {
                    return ['status' => 0, 'message' => "炁点不足，当前炁点" . $UserInfo['balance_2']];
                }else{
                    $UserSave['balance_2'] = $UserInfo['balance_2'] - $Data['num'];
                    $UserSave['balance_3'] = $UserInfo['balance_3'] + $Data['num'] / $Config['parameter_3'];
                }
            }

            if($Data['type'] == 1){ //奖金转换电子钱包
                if ($Data['num'] > $UserInfo['balance_1']) {
                    return ['status' => 0, 'message' => "奖金不足，当前奖金" . $UserInfo['balance_1']];
                }else{
                    $UserSave['balance_1'] = $UserInfo['balance_1'] - $Data['num'];
                    $UserSave['balance_4'] = $UserInfo['balance_4'] + $Data['num'];
                }
            }

            //更新余额
            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave)){
                FinanceAdd($UserInfo['id'],$UserInfo['id'],$Data['num'],$Data['type'],'12','转换股权');

                return ['status' => 1, 'message' => "转换成功"];
            }else{
                return ['status' => 0, 'message' => "系统错误，请稍后再试"];
            }
        }

        //转出/转进记录
        $Map['reward_type'] = array('in','12');
        $Map['user_id'] = $UserInfo['id'];
        $FinanceList = Db::name('finance')->where($Map)->order('id desc')->select();
        foreach($FinanceList as $k=>$v){
            $User = UserInfo(['id'=>$FinanceList[$k]['from_id']]);
            $FinanceList[$k]['username'] = $User['username'];
        }
        $this->assign('FinanceList',$FinanceList);

        return $this->fetch('UserRechange');
    }

    /**
     * 修改登录密码
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function UserPass(){
        if(IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>Session::get('user_id')]);

            if(md5($Data['old_password']) != $UserInfo['password_login']){
                return ['status'=>0,'message'=>'原密码错误'];
            }
            if(md5($Data['new_password']) == $UserInfo['password_login']){
                return ['status'=>0,'message'=>'新旧密码一致,无需更改'];
            }

            $SaveData['password_login'] = md5($Data['new_password']);
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($SaveData)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        return $this->fetch('UserPass');
    }

    /**
     * 修改支付密码
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function UserPassPay(){
        if(IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>Session::get('user_id')]);

            if(md5($Data['old_password']) != $UserInfo['password_pay']){
                return ['status'=>0,'message'=>'原密码错误'];
            }
            if(md5($Data['new_password']) == $UserInfo['password_pay']){
                return ['status'=>0,'message'=>'新旧密码一致,无需更改'];
            }

            $SaveData['password_pay'] = md5($Data['new_password']);
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($SaveData)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        return $this->fetch('UserPassPay');
    }

    //手机号修改
    public function Userphone(){
        if(IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>Session::get('user_id')]);

            //手机号是否正确
            if(!$this ->is_mobile($Data['new_phone'])){
                return ['status'=>0,'message'=>'手机号格式不对'];
            }

            //判断验证码是否正确
            $CodeRes = checkCode($UserInfo['phone'],$Data['code']);
            // var_dump($CodeRes);die;
            if($CodeRes['status'] != 1){
                return $CodeRes;
            }

            //手机号是否重复
            $pd = Db::name('user')->where(['phone'=>$Data['new_phone']])->find();
            if($pd){
                return ['status'=>0,'message'=>'手机号已存在'];
            }

            $SaveData['phone'] =$Data['new_phone'];
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($SaveData)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        return $this->fetch('Userphone');
    }

    function is_mobile($user_mobile){

        $chars = "/^((\(\d{2,3}\))|(\d{3}\-))?1(3|4|5|6|7|8|9)\d{9}$/";

        if (preg_match($chars, $user_mobile)){

            return true;

        }else{

            return false;

        }

    }

    public function Userphone_1(){
        if(IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
            //手机号是否正确
            if(!$this ->is_mobile($Data['new_phone'])){
                return ['status'=>0,'message'=>'手机号格式不对'];
            }
            //手机号是否重复
            $pd = Db::name('user')->where(['phone'=>$Data['new_phone']])->find();
            if($pd){
                return ['status'=>0,'message'=>'手机号已存在'];
            }

            $SaveData['phone'] =$Data['new_phone'];
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($SaveData)){
                return ['status'=>1,'message'=>'绑定成功'];
            }else{
                return ['status'=>0,'message'=>'绑定失败'];
            }
        }
        return $this->fetch('Userphone_1');
    }

    /**
     * 会员二维码
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserQrcode(){
        //判断当前会员是否已生成二维码
        $Qrcode = Db::name('user_qrcode')->where(['user_id'=>Session::get('user_id')])->find();

        //如果没有则生成
        if(empty($Qrcode)){
            //会员信息
            $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
            $url = 'http://'.$_SERVER['HTTP_HOST'] . '/index.php/Open/login.html?&recommend='.$UserInfo['username'];
            $qrpath = $this->addQrcode($url,$UserInfo['id']);
//            $image = \think\Image::open($qrpath)->thumb(200,200,\Think\Image::IMAGE_THUMB_FIXED)->save($qrpath);//修改二维码尺寸;
            $qrpath = 'http://'.$_SERVER['HTTP_HOST'] . '/uploads/qrcode/' . $UserInfo['id'].'.png';
            $QrcodeAdd['user_id'] = $UserInfo['id'];
            $QrcodeAdd['url'] = $qrpath;
            Db::name('user_qrcode')->insert($QrcodeAdd);
        }else{
            $qrpath = $Qrcode['url'];
        }
        $this->assign('QrCodeUrl',$qrpath);

        //推荐会员
        $RecommendList = Db::name('user')->where(['recommend'=>Session::get('user_id')])->order('add_time desc')->select();
        foreach($RecommendList as $k=>$v){
            $LevelInfo = LevelInfo(['id'=>$RecommendList[$k]['level']]);
            $RecommendList[$k]['level_name'] = $LevelInfo['name'];
        }
        $this->assign('RecommendList',$RecommendList);

        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        return $this->fetch('UserQrcode');
    }

    /**
     * 二维码生成
     * @param $url
     * @param $id
     * @return string
     */
    public function addQrcode($url,$id){
        Vendor('phpqrcode.phpqrcode');
        //生成二维码图片
        $object = new \QRcode();

        $path = $_SERVER['DOCUMENT_ROOT']."/uploads/qrcode/";

        $ad = $path.$id.'.png';
        $errorCorrectionLevel ='L' ;//容错级别
        $matrixPointSize = 6;//生成图片大小

        $object->png($url,  $ad, $errorCorrectionLevel, $matrixPointSize, 2);
        return $ad;
    }

    /**
     * 我的团队
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserTeam(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        //我推荐的
        $TeamList = Db::name('user')->where(['recommend'=>Session::get('user_id')])->order('add_time desc')->select();
        foreach ($TeamList as $k=>$v){
            //等级信息
            if($TeamList[$k]['level'] == 0){
                $TeamList[$k]['level_name'] = '普通用户';
            }else{
                $LevelInfo = LevelInfo(['id'=>$TeamList[$k]['level']]);
                $TeamList[$k]['level_name'] = $LevelInfo['name'];
            }
        }
        $this->assign('TeamList',$TeamList);

        return $this->fetch('UserTeam');
    }

    /**
     * 会员推荐图
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function RecommendMap(){
        // //查找的用户名
        // $UserName = Param('username');
        // if(empty($UserName)){
        //     $UserName = "admin";
        // }

        // //会员信息
        // $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        // if($UserInfo){
        //     $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
        //     $UserInfo['level_name'] = $LevelInfo['name'];
        //     $Data = array('name' =>$UserInfo['username'].'|'.$UserInfo['name'].'|'.$UserInfo['level_name'],'children'=>$this->SelectSon($UserInfo['id']));       //父节点  Pid=1;
        //     $Data = json_encode($Data);
        // }else{
        //     $Data = null;
        // }
        // $this->assign("Data",$Data);
        // return $this->fetch('RecommendMap');
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        //获取所有下级  自己不显示
//        $ids = Db::name('user_recommend')->where(['recommend_id'=>$UserInfo['id'],'layer'=>['gt',0]])->column("user_id");
//        foreach ($ids as $v){
//            $info = UserInfo(['id'=>$v]);
//            $infos[] = $info;
//        }
//        $this->assign("infos",$infos);
        $where['recommend'] = $UserInfo['id'];
        if(Param('id')){
            $where['recommend'] = Param('id');
        }

        $infos = Db::name('user')->where($where)->select();
        $all = [];
        foreach ($infos as $v){
            $LevelInfo = LevelInfo(['id'=>$v['level']]);
            $v['level_name'] = $LevelInfo['name'];
            $all[] = $v;
        }
        $this->assign("infos",$all);
        return $this->fetch('RecommendMap_1');
    }

    /**
     * 推荐图寻找下级接点
     * @param $higher_id
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public  function SelectSon($Recommend){
        $UserInfo = UserInfo(["id"=>Session::get("user_id")]);

        $Where['recommend'] = $Recommend;
        $UserList = Db::name('user')->where($Where)->select();
        if($UserList){  //查找该父ID下的子ID
            $Data = array();
            for ($i=0; $i < count($UserList) ; $i++)
            {
                $LevelInfo = LevelInfo(['id'=>$UserList[$i]['level']]);
                $UserList[$i]['level_name'] = $LevelInfo['name'];

                $Layer = Db::name("user_recommend")->where(["user_id"=>$UserList[$i]["id"],"recommend_id"=>$UserInfo["id"]])->value("layer");
                if($Layer <= 2){
                    $da=array('name' =>$UserList[$i]['username'].'|'.$UserList[$i]['name'].'|'.$UserList[$i]['level_name'],'children'=>$this->SelectSon($UserList[$i]['id']));  //递归算法！

                    array_push($Data, $da);//加入子节点数组
                }

            };
            return $Data;//一次性返回子节点数组，他们成为同级子节点。
        } else{
            return null;
        }
    }

    /**
     * 反馈记录
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Feedback(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $Feedback = Db::name('feedback')->where(['user_id'=>$UserInfo['id']])->order('id desc')->select();
        $this->assign('Feedback',$Feedback);

        return $this->fetch('Feedback');
    }

    /**
     * 提交反馈
     * @return array|mixed
     */
    public function FeedbackAdd(){
        if(IsPost()){
            $AddData = [
                'user_id' => Session::get('user_id'),
                'content' => Param('content'),
                'add_time' => time(),
            ];

            if(Db::name('feedback')->insert($AddData)){
                return ['status'=>1,'message'=>'反馈已提交'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请稍后再试'];
            }
        }
        return $this->fetch('FeedbackAdd');
    }

    /**
     * 反馈详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function FeedbackDetail(){
        $FeedbackInfo = FeedbackInfo(['id'=>Param('id')]);
        $this->assign('FeedbackInfo',$FeedbackInfo);

        return $this->fetch('FeedbackDetail');
    }

    /**
     * 反馈删除
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function FeedbackDel(){
        if(IsPost()){
            if(Db::name('feedback')->delete(['id'=>Param('id')])){
                return ['status'=>1,'message'=>'反馈已删除'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请稍后再试'];
            }
        }
    }

    /**
     * 多图上传
     */
    public function forUpload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');

        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>1567800000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads/head');

        if($info){
            //返回上传图片路径
            $path = "/uploads/head/".$info->getSaveName();
            return ['status'=>1,'message'=>$path];
        }else{
            // 上传失败获取错误信息
            return ['status'=>0,'message'=>$file->getError()];
        }
    }

    /**
     * 获取用户姓名
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function CheckUser(){
        $UserInfo = UserInfo(['phone'=>Param('username')]);
        if(empty($UserInfo)){
            $Message = '用户不存在';
        }else{
            $Message = $UserInfo['name'];
        }
        return ['status'=>1,'message'=>$Message];
    }
    
    //签到
    public function qiandao(){
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        if($UserInfo['qiandao'] != date('Y-m-d')){
            //签到奖金
            $qian = Config()['qiandao'];
            $date['balance_1'] = $UserInfo['balance_1'] + $qian;
            $date['qiandao'] = date('Y-m-d');
            Db::name('user')->where(['id'=>$UserInfo['id']])->setInc('countqian',1);//签到累积天数
            FinanceAdd($UserInfo['id'], $UserInfo['id'], $qian, 1, 11, '签到积分');
            Db::name('user')->where(['id'=>$UserInfo['id']])->update($date);
            return ['status'=>2,'message'=>'签到成功'];
        }else{
            return ['status'=>2,'message'=>'已签到,请勿重复签到'];
        }
    }
    
    //检查有无手机号\
    public function checkphone(){
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        if(!$UserInfo['phone']){
            return ['status'=>2,'message'=>'请先填写手机号'];
        }else{
            return ['status'=>1,'message'=>'可接受短信'];
        }
    }
}
